package com.woniu.shop.task;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.shop.constant.RedisConstant;
import com.woniu.shop.mapper.ShopIncomeMapper;
import com.woniu.shop.pojo.ShopIncome;
import com.woniu.shop.pojo.ShopYearIncome;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author LiFangyu
 * @since 2023/2/22 9:53
 */
@Configuration
@Slf4j
public class GenerateAllYearIncomeTask implements SchedulingConfigurer {

    @Autowired
    private ShopIncomeMapper shopIncomeMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                // 定时任务执行代码块:() -> {executeTask();}
                this::executeTask,
                // 指定下一次任务执行的表达式
                triggerContext -> {
                    String cron = shopIncomeMapper.getCron(this.getClass().getName().substring(0,this.getClass().getName().indexOf("$")));
                    if(StringUtils.isEmpty(cron)){
                        log.debug("定时任务表cron表达式为空，请检查");
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }

    /**
     * 定时任务执行的业务
     */
    @PostConstruct
    private void executeTask(){
        System.out.println("定时任务执行中：" + new Date());
        // 1.获取所有的门店
        List<String> shopIds = shopIncomeMapper.getAllShopId();
        // 2.对每个门店每年的收益进行统计
        for(String shopId : shopIds){
            // 根据门店id查询收益表中所有的年份
            List<String> allYear = shopIncomeMapper.getAllYear(shopId);
            for(String year : allYear){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                if(!year.equals(String.valueOf(calendar.get(Calendar.YEAR)))){ // 非本年时执行
                    BigDecimal amount = new BigDecimal(0);
                    List<ShopIncome> shopIncomes = shopIncomeMapper.getIncomeRecord(shopId, year);
                    // 将年收益的记录保存到redis中
                    if(shopIncomes != null){
                        ObjectMapper objectMapper = new ObjectMapper();
                        String records = null;
                        try {
                            records = objectMapper.writeValueAsString(shopIncomes);
                        } catch (JsonProcessingException e) {
                            log.error("json转换异常，异常的信息为{}", shopIncomes);
                            e.printStackTrace();
                        }
                        stringRedisTemplate.opsForHash().put(RedisConstant.SHOP_YEAR_INCOME_LIST.name() + "_" + shopId, year, records);
                        // 统计每笔收益的金额
                        for(ShopIncome shopIncome : shopIncomes){
                            amount = amount.add(shopIncome.getAmount());
                        }
                        ShopYearIncome shopYearIncome = new ShopYearIncome();
                        shopYearIncome.setId(IdWorker.getIdStr());
                        shopYearIncome.setShopId(shopId);
                        shopYearIncome.setAmount(amount);
                        shopYearIncome.setYear(year);
                        shopYearIncome.setIsDeleted("0");
                        Date date = new Date();
                        shopYearIncome.setCreatedTime(date);
                        shopYearIncome.setUpdatedTime(date);
                        // 将年收益保存到数据库，先判断是否有数据
                        ShopYearIncome check = shopIncomeMapper.checkRecordExist(shopId, year);
                        if(StringUtils.isEmpty(check)){
                            shopIncomeMapper.createShopYearIncome(shopYearIncome);
                        }else if (check.getAmount().compareTo(amount) != 0){
                            shopIncomeMapper.updateShopYearIncome(shopYearIncome);
                        }
                        // 将年收益保存到redis
                        String income = null;
                        try {
                            income = objectMapper.writeValueAsString(amount);
                        } catch (JsonProcessingException e) {
                            log.error("json转换异常，异常的信息为{}", amount);
                            e.printStackTrace();
                        }
                        stringRedisTemplate.opsForHash().put(RedisConstant.SHOP_YEAR_INCOME_AMOUNT.name() + "_" + shopId, year, income);
                    }
                }
            }
        }
    }

}
